import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { QCLOUD_DOMAIN, UPLOAD_DOMAIN } from '../../constant/config';
import { NzMessageService, NzModalRef } from 'ng-zorro-antd';
import { CacheService } from '@core/routes-services/cache.service';

@Component({
  selector: 'simple-editor',
  templateUrl: './simple-editor.component.html',
  styleUrls: ['./simple-editor.component.scss'],
})
export class SimpleEditorComponent implements OnInit, OnDestroy {

  contentVal: any = '';
  uploadDomain = UPLOAD_DOMAIN;
  qcloudDomain = QCLOUD_DOMAIN;
  imgList: any[] = [];
  headers: any = {};
  btns: any = '<div class="img-btns ignore-area" id="img-btns" style="position:absolute;background-color:rgba(0,0,0,0.3);border-radius:1px;color: #fff;padding:16px 10px;border: 1px solid rgb(16, 142, 233);">' +
    // '<span class="ignore-area img-btn-title" id="img-btn-title" style="margin: 0 3px;padding:0 2px;border:1px solid #fff;">添加图说明</span>' +
    '<span class="ignore-area img-btn-del" id="img-btn-del" style="margin: 0 3px;padding:0 2px;border:1px solid #fff;cursor: pointer;">删除</span>' +
    '<span class="ignore-area img-btn-up" id="img-btn-up" style="margin: 0 3px;padding:0 2px;border:1px solid #fff;cursor: pointer;">上移</span>' +
    '<span class="ignore-area img-btn-down" id="img-btn-down" style="margin: 0 3px;padding:0 2px;border:1px solid #fff;cursor: pointer;">下移</span>' +
    '</div>';

  event: any = null;
  eventDivId: any = null;

  @ViewChild('content') contentEl: ElementRef;

  constructor(private modal: NzModalRef,
              private cacheService: CacheService,
              private message: NzMessageService) {
  }

  ngOnInit() {
    const token: any = this.cacheService.getTokenInfo();
    this.headers = { 'Authorization': token };
    this.contentVal = this.contentVal ? this.contentVal : '';
    this.contentEl.nativeElement.innerHTML = this.contentVal;
    document.body.addEventListener('click', this.toShowBtn);
  }

  ngOnDestroy(): void {
    document.body.removeEventListener('click', this.toShowBtn);
  }


  /**
   * 上传图控件 ng-zorro upload
   *
   * @param {any} file
   * @param {any} fileList
   */
  handleChange({ file, fileList }): void {
    const status = file.status;
    if (status !== 'uploading') {
      // console.log(file, fileList);
    }
    if (status === 'done') {
      this.message.success(`${file.name} 上传成功`);
      let findIdx = fileList.findIndex(w => file.lastModified == w.lastModified);
      fileList[findIdx].imgKey = fileList[findIdx].response.data;
      fileList[findIdx].name = fileList[findIdx].response.data;
      fileList[findIdx].url = this.qcloudDomain + fileList[findIdx].response.data;
      fileList[findIdx].elId = Number(new Date());
      // console.log(this.imgList)
      this.contentVal = this.contentVal + '<div style="line-height: 0;" id="img' + fileList[findIdx].elId + '">\n' +
        '  <img  alt="加载失败" class="content-img" style="width: 100%; cursor: pointer; border: none;" src="' + fileList[findIdx].url + '" id="' + fileList[findIdx].elId + '">\n' +
        '    </div>';
      this.contentEl.nativeElement.innerHTML = this.contentVal;
    } else if (status === 'error') {
      this.message.error(`${file.name} 上传失败`);
    }
  }

  /**
   * 点击图显示/去除操作按钮
   *
   * @param e
   */
  toShowBtn = (e) => {//<HTMLInputElement>
    let $this = this;
    let $Target = e.target;
    if ($Target.className.toString().includes('content-img')) {
      if ($Target.style.border && $Target.style.border != 'none') {
        $Target.style.border = 'none';
        document.getElementById('img-btns') ? document.getElementById('img-btns').remove() : null;
        $this.event = null;
      } else {
        $this.cleanOther();
        $this.event = e;
        $Target.style.border = '1px solid #108ee9';
        // console.log($Target.id);
        $this.eventDivId = $Target.id;
        let $inputDoc = document.getElementById('input' + $this.eventDivId);
        if ($inputDoc) {
          $Target.parentNode.innerHTML = $this.btns.replace('添加图说明', '移除图说明') + $Target.parentNode.innerHTML;
        } else {
          $Target.parentNode.innerHTML = $this.btns + $Target.parentNode.innerHTML;
        }
        document.getElementById('img-btn-del').addEventListener('click', function(e) {
          $this.delImg(e);
        });
        document.getElementById('img-btn-up').addEventListener('click', function(e) {
          let $dom = null;
          let children = document.getElementById('content').children;//在此范围内找，否则会找到父组件中的
          for (let i = 0; i < children.length; i++) {
            // console.log(children[i].id)
            if (children[i].id == 'img' + $this.eventDivId) {
              $dom = children[i];
            }
          }
          let $pre = $dom.previousElementSibling;
          if ($pre != null) {
            let $parentNode = $dom.parentNode;
            $parentNode.insertBefore($dom, $pre);
          }

        });
        document.getElementById('img-btn-down').addEventListener('click', function(e) {
          let $dom = null;
          let children = document.getElementById('content').children;//在此范围内找，否则会找到父组件中的
          for (let i = 0; i < children.length; i++) {
            // console.log(children[i].id)
            if (children[i].id == 'img' + $this.eventDivId) {
              $dom = children[i];
            }
          }
          let $next = $dom.nextElementSibling;
          if ($next != null) {
            let $parentNode = $dom.parentNode;
            $parentNode.insertBefore($next, $dom);
          }
        });
        // document.getElementById('img-btn-title').addEventListener('click', function (e) {
        //   $this.addTitle(e);
        // });
      }
    } else if ($Target.className.toString().includes('ignore-area')) {
      //忽略
    } else {
      $this.cleanOther();
    }
  };

  /**
   * 去除图选中样式及按钮
   *
   */
  cleanOther() {
    let $this = this;
    let imgDom: any = document.getElementsByClassName('content-img');
    Array.prototype.forEach.call(imgDom, function(item, index, arr) {
      item.style.border = 'none';
      document.getElementById('img-btns') ? document.getElementById('img-btns').remove() : null;
      $this.event = null;
    });
  }


  /**
   * 图添加/移除文字输入框
   *
   * @param e
   */
  addTitle(e) {
    let $this = this;
    let $inputDoc = document.getElementById('input' + this.eventDivId);
    if ($inputDoc) {
      $inputDoc.remove();
      e.target.innerHTML == '添加文章说明' ? e.target.innerHTML = '移除图说明' : e.target.innerHTML = '添加图说明';
    } else {
      let doc = document.getElementById('img' + this.eventDivId);
      let html = doc.innerHTML;
      let inputEle = document.createElement('input');
      inputEle.id = 'input' + this.eventDivId;
      inputEle.style.width = '100%';
      inputEle.placeholder = '添加图说明';
      doc.innerHTML = inputEle.outerHTML + html;
      inputEle.focus();
      document.getElementById('input' + this.eventDivId).focus();
      $this.cleanOther();
    }
  }


  /**
   * 删除图
   *
   * @param e
   */
  delImg(e) {
    let children = document.getElementById('content').children;//坑：在此范围内找，否则会找到父组件中的
    for (let i = 0; i < children.length; i++) {
      // console.log(children[i].id)
      if (children[i].id == 'img' + this.eventDivId) {
        children[i].remove();
      }
    }
  }


  /**
   * 获取输入信息html信息 测试按钮
   */
  getContent() {
    this.cleanOther();
    console.log(document.getElementById('content').innerHTML);

  }

  emitDataOutside() {
    this.cleanOther();
    this.contentVal = document.getElementById('content').innerHTML;
    this.modal.close(this.contentVal);
  }

  close() {
    this.modal.destroy();
  }
}
